<?php
namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\FamousSchool;
use App\Models\File;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

/**
 * Created by PhpStorm.
 * User: 都大爽
 * Date: 2017/6/27
 * Time: 15:39
 */
class FamousSchoolController extends Controller
{

    /**
     * 名校列表
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request)
    {
        $keyword = $request->get('keyword', '');
        $query = FamousSchool::query()->when($keyword , function ($queryString) use ($keyword) {
            return $queryString->where('sort', $keyword );
        })->with('file')->orderBy('sort' , 'asc');
        $models = $query->paginate();
        return $models;
    }


    /**
     * 添加一个新的名校
     * @param Request $request
     * @return FamousSchool|\Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function store(Request $request)
    {
        $data = $request->all();
        $validator = Validator::make($data,
            [
                'sort' => 'required',
                'file_id' => 'required'
            ],
            [
                'sort.required' => '排序必填',
                'file_id.required'  => '图片未上传'
            ]
        );
        if ($validator->fails()) {
            $errors = $validator->errors();
            return response($errors, 422);
        }
        $model = new FamousSchool();
        $model->sort = $data['sort'];
        $model->file_id = $data['file_id'];
        if ($model->save()){
            return $model;
        }else{
            return response($model->getErrors()->toArray(), 406);
        }
    }

    /**
     * 更新名校
     * @param Request $request
     * @param $modelId
     * @return FamousSchoolController|\Illuminate\Contracts\Routing\ResponseFactory|mixed|\Symfony\Component\HttpFoundation\Response
     */
    public function update(Request $request, $modelId)
    {
        $data = $request->all();
        $validator = Validator::make($data,
            [
                'sort' => 'required',
                'file_id' => 'required'
            ],
            [
                'sort.required' => '排序必填',
                'file_id.required'  => '图片未上传'
            ]
        );
        if ($validator->fails()) {
            $errors = $validator->errors();
            return response($errors, 422);
        }
        $model = $this->findModel($modelId);
        $model->sort = $data['sort'];
        $model->file_id = $data['file_id'];
        if ($model->save()){
            return $model;
        }else{
            return response($model->getErrors()->toArray(), 406);
        }
    }


    /**
     * 获取名校
     * @param $modelId
     * @return FamousSchoolController|mixed
     */
    public function show($modelId)
    {
        $model = $this->findModel($modelId);
        $model->path = $model->file->path;
        return $model;
    }


    /**
     * 加载名校
     * @param $modelId
     * @return mixed|static
     */
    public function findModel($modelId)
    {
        $model = FamousSchool::find($modelId);
        return $model;
    }


    /**
     * 删除名校
     * @param $modelId
     * @return array
     */
    public function destroy($modelId)
    {
        $model = $this->findModel($modelId);
        try{
            $model->delete();
            Storage::delete($model->file->path);
            return ['state' => 'success'];
        }catch (\Exception $e) {
            return ['state' => 'failed', 'message' => $e->getMessage()];
        }
    }


    /**
     * 上传名校图片
     * @param Request $request
     * @return array|\Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function fileUpload(Request $request)
    {
        if ($request->file('file')){
            $file = $request->file('file');
            $img = new File();
            $img->type = '名校图片';
            $img->size = $file->getSize();
            $path = Storage::put('famous-schools', $file);
            if ($path){
                $img->path = $img->key = $path;
                $img->filename = pathinfo($path , PATHINFO_BASENAME);
                $img->extension = pathinfo($path , PATHINFO_EXTENSION);
            }else{
                return response(['upload_failed' => '上传失败'], 422);
            }
            if ($img->save()){
                return ['status' => 'success', 'file_id' => $img->id, 'path' => $img->path];
            }else{
                return response($img->getErrors()->toArray(), 406);
            }
        }
    }
}